package com.moter.one.wyydemo1.controller;

import com.moter.one.wyydemo1.backstage.vo.DataVo;
import com.moter.one.wyydemo1.entity.UserInfo;
import com.moter.one.wyydemo1.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import javax.xml.crypto.Data;
import java.util.List;

@RestController
public class Login {
    @Autowired
    UserInfoService userInfoService;
    @RequestMapping("/user/login")
    public DataVo<UserInfo> LoginUser(@RequestBody UserInfo user, HttpSession session){
        String username = user.getAccount();
        String password = user.getPassword();
//        System.out.println(username + " " + password);
        List<UserInfo> list = userInfoService.searchAllUsers();//找到所有用户信息
        UserInfo userInfo = new UserInfo();
        userInfo.setAccount(username);//添加用户信息
        userInfo.setPassword(password);
        if(list == null || list.size()==0){
            //登录失败
            DataVo<UserInfo> dataVo = new DataVo<UserInfo>(1,"登陆失败",userInfo,123);
            return dataVo;
        }
        int i = Judge_Right(username,password,list);
        if(i == 1){
            //登录成功  在session中加入信息
            session.setAttribute("account", username);
            DataVo<UserInfo> dataVo = new DataVo<UserInfo>(0,"登陆成功",userInfo,123);
            return dataVo;
        }
        else {
            //登陆失败
            DataVo<UserInfo> dataVo = new DataVo<UserInfo>(1,"登陆失败",userInfo,123);
            return dataVo;
        }
    }
    public int Judge_Right(String username,String password,List<UserInfo> list){
          for(int i=0;i<list.size();i++){
              if(username.equals(list.get(i).getAccount())){//账号相等
//                  System.out.println(list.get(i).getAccount()+" "+list.get(i).getPassword());
                  if(password.equals(list.get(i).getPassword())){//密码相等
                      return 1;//登陆成功
                  }
                  return 0;
              }
          }
          return 0;
    }
}
